package com.aaa.sys.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

/**
 * @author lei chu
 * @since 2021/2/21 20:12
 */
@Component
public class OssUploadUtil {
    @Value("${oss.endpoint}")
    private String endpoint;
    @Value("${oss.accesskeyId}")
    private String accesskeyId;
    @Value("${oss.accessKeySecret}")
    private String accessKeySecret;
    @Value("${oss.bucketName}")
    private String bucketName;

    private OSS ossClient;

    public String upload(MultipartFile file) {
        try{
            // 创建OSSClient实例。
            ossClient = new OSSClientBuilder().build(endpoint, accesskeyId, accessKeySecret);
            // 上传文件流。
            InputStream inputStream = file.getInputStream();
            String fileName = UUID.randomUUID()+file.getOriginalFilename();
            ossClient.putObject(bucketName, fileName, inputStream);
            String url = "https://"+bucketName+"."+endpoint+"/"+fileName;
            return url;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }finally {
            // 关闭OSSClient。
            ossClient.shutdown();
        }
    }


}
